package com.atguigu.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 前端根据不同用户 不同权限，加载不同的界面
 * 用thymeleaf-extras-springsecurity5集成的东西控制
 * <div sec:authorize="hasRole('vip1')></div>
 *
 * @author sx
 * @date 2022-02-22 15:33
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 授权
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //请求授权规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限，默认回到登录页面
//        http.formLogin();
        //定制登录页、账号和密码对应的前后端映射名
        http.formLogin().loginPage("/toLogin")
                .usernameParameter("user")
                .passwordParameter("pwd")
                .loginProcessingUrl("/login");

        //防止网站攻击，关闭csrf功能
        http.csrf().disable();
        //注销
        http.logout().logoutSuccessUrl("/");

        //记住我 cookie默认保存两周
        // 自定义接受前端参数 <input type="checkbox" name="remember">记住我
        http.rememberMe().rememberMeParameter("remember");
    }

    /**
     * 认证配置
     * @param auth
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //这些数据应该从数据库查
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("songxi").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("custom").password(new BCryptPasswordEncoder().encode("123456")).roles("vip3");
    }
}
